<template>
  <div class="container" style="margin-bottom:50px">
    <div class="title-box">
      <span class="title">快速下单系统</span>
    </div>
    <div class="menu">
      <ul>
        <li class="current" id="eleCartNav" onclick="selectCar_click(this)">
          <i class="icon-car"></i>
          <span>购物车</span>
        </li>
      </ul>
      <ul id="eleDarftMenu" class="darft-memu"></ul>
    </div>
    <!-- 购物车部分-->
    <div id="eleCarOrder" style="display: block;">
      <!-- <el-checkbox-group v-model="checkList"> -->
      <div class="border-box">
        <div class="add-darft-box">
          <div class="wrap">
            <div class="left">
              <div>
                <label
                  class="name"
                  style="display: none; max-width: 400px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;"
                  id="eleDarftName"
                ></label>
                <i class="icon-edit" style="display: none;" onclick="editDart_click()"></i>
              </div>
              <p>
                共
                <span class="product-count">{{cartsRes.length}}</span>种商品，已选择
                <span class="select-type-count">{{cartsRes.length}}</span>种
                <span class="select-product-count*------------">{{znum}}</span>件商品
              </p>
            </div>
            <div class="time-darft">
              <div>
                <label>创建时间</label>
                <p id="dcreate_time" style="width: 200px;"></p>
              </div>
              <div>
                <label>修改时间</label>
                <p id="dmodi_time" style="width: 200px;"></p>
              </div>
            </div>
          </div>
        </div>
        <div class="content">
          <table class="car_table">
            <tbody>
              <tr>
                <!--              <th width="40">-->
                <!--                <input type="checkbox" onclick="check_all(this)" class="check_all" checked="">-->
                <!--              </th>-->
                <th>勾选</th>
                <th>序号</th>
                <th width="70">品牌</th>
                <!--              <th width="120">订货号</th>-->
                <th width="180">产品型号</th>
                <th width="160">数量</th>
                <!-- <th width="60">库存</th>
                <th width="150">货期</th>-->
                <th>市场价</th>
                <th>折扣</th>
                <th>会员价</th>
                <th width="100">小计</th>
                <th width="50">操作</th>
              </tr>
            </tbody>

            <tbody id="eleCarList" v-for="(itema,indexa) in carts" :key="indexa">
              <td>{{itema.name}}</td>
              <tr v-for="(item, index) in itema.origin" :key="item.id">
                <td>
                  <input type="checkbox" :value="item.id" v-model="checkList" />
                </td>
                <td class="car-no-6592559">{{index + 1}}</td>
                <td>{{item.product.brand_name}}</td>
                <td>
                  <a href="/detail/product_6299.html" target="_blank">{{item.product.model_name}}</a>
                </td>
                <td>
                  <div class="edit">
                    <el-input-number
                      v-model="item.amount"
                      @change="amountChange(indexa,index)"
                      :min="1"
                    ></el-input-number>
                  </div>
                </td>
                <td>¥{{item.product.price}}</td>
                <td>1</td>
                <td>¥{{Number(item.product.discount_price.toString().match(/^\d+(?:\.\d{0,2})?/))}}</td>
                <td class="font-red">¥{{item.totalPrice}}</td>
                <td>
                  <el-button type="text" @click="open(item)">
                    <svg-icon icon-class="delete" class-name="delete" />
                  </el-button>
                </td>
              </tr>
              <!-- </el-checkbox-group> -->
            </tbody>
          </table>
          <div class="search-box" style="display: none;">
            <input
              type="text"
              id="txtOrderKeyword"
              class="input-search"
              placeholder="请输入型号或订货号，添加产品"
            />
            <ul class="item-box" id="eleSearchOrderResult">
              <!-- <li><label>"XB2-BA42C (ZB2BZ102C)</label><span>(RDFSF-3343)</span><div class="add"><input type="number" value="1" /><i class="icon-add"></i></div></li>
              <li><label>"XB2-BA42C (ZB2BZ102C)</label><span>(RDFSF-3343)</span></li>-->
            </ul>
            <span class="status" id="eleAddStatus"></span>
          </div>
          <div class="m-add-box">
            <div class="example">
              <p class="t1">批量添加订货号和数量，用空格隔开（可从Excel复制）。 如：</p>
              <p>ZB2BZ102C 50</p>
              <p>A9P18620 20</p>
              <p>RXZE2S114M 30</p>
              <p>XB2BA42C 60</p>
              <p>ZB2BD2C 80</p>
              <div class="tips">
                <!-- <svg-icon icon-class="tips" class-name="svg-tips" /> -->
                <span class="z_icon">注</span>
                <p>购物车产品行数上限为500行，建议您参考如下操作：</p>
                <p>1.购物车内的产品，先下单或转为草稿；</p>
                <p>2.将批量下单的产品，分批次下单；</p>
              </div>
            </div>
            <textarea v-model="info" @blur="infoBlur"></textarea>
            <div class="margin10">
              <button
                type="button"
                class="btn-add button bgff0000"
                style="margin-top:-5px;border-radius:3px"
                @click="addFastCart"
                data-track="批量添加_智能下单"
              >添加</button>
              <a id="a_download_template" href="/download_file/Mould.xlsx" class="bg4448f8">下载模板</a>
            </div>
          </div>
        </div>
      </div>
      <div style="text-align: right; margin-top: 30px;">
        <label>总价(不含运费)：</label>
        <span style="color: #ec605f; font-size: 16px;" id="eleAmount">￥{{total}}</span>
      </div>
      <!--      <div class="remark mt30 clearfix">-->
      <!--        <input type="text" v-model="remark" placeholder="请输入备注" id="txtDarftRemark">-->
      <!--        <label class="remark" style="display: none" id="eleDarftRemark"></label>-->
      <!--      </div>-->
      <div class="submit-box">
        <!--        <a href="javascript:void(0)" class="bg4448f8" id="btnExportOrder" onclick="exportOrder_click(this)">导出报价单</a>-->
        <!--        <a href="javascript:void(0)" class="bgff0000" id="btnTransOrder" onclick="transOrder_click()">转换询价单</a>-->
        <a href="#" class="order" id="btnAddOrder" style="border-radius:3px" @click="addOrder">生成订单</a>
        <a href="#" id="hidBtnExportOrder" style="display:none;"></a>
      </div>
    </div>
    <!--购物车结束-->
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import { cartList, removeCart, fastCarts, deitCart } from "@/api/cart";
import { NumberMul, NumberAdd } from "@/utils/number";
import { storeCartList } from "@/api/business";
export default {
  name: "Cart",
  metaInfo: {
    title: "我的购物车",
    titleTemplate: "工流界MRO一站式采购商城"
  },
  data() {
    return {
      carts: [],
      total: 0,
      remark: "",
      addressList: [],
      addressActive: "",
      info: "",
      znum: 0,
      checkList: [],
      cartsRes: []
    };
  },
  created() {
    this.fetchCarts();
    this.setHasNav(false);
  },
  watch: {},
  methods: {
    ...mapMutations({
      setHasNav: "app/SET_PAGE_HAS_NAV"
    }),
    async fetchCarts() {
      const res = await cartList();
      this.cartsRes = res;
      const cartsData = res.map(item => {
        item.totalPrice = parseFloat(
          item.amount * item.product.discount_price
        ).toFixed(2);
        return item;
      });
      res.forEach(item => {
        this.checkList.push(item.id);
      });
      let afterData = [];
      let tempArr = [];
      for (let i = 0; i < cartsData.length; i++) {
        if (tempArr.indexOf(cartsData[i].business_id) === -1) {
          let datsd = {
            business_id: cartsData[i].business_id,
            name: cartsData[i].business.name || "工流界自营",
            origin: [cartsData[i]]
          };
          afterData.push(datsd);
          tempArr.push(cartsData[i].business_id);
        } else {
          for (let j = 0; j < afterData.length; j++) {
            if (afterData[j].business_id == cartsData[i].business_id) {
              afterData[j].origin.push(cartsData[i]);
              break;
            }
          }
        }
      }
      this.carts = afterData;
      if (res.length) {
        this.totalAmount();
        res.forEach(item => {
          this.znum += parseInt(item.amount);
        });
      }
    },
    amountChange(indexa, index) {
      console.log(index + "值改变");
      console.log(this.carts[indexa].origin[index].amount + "数量改变");
      this.carts[indexa].origin[index].totalPrice =
        this.carts[indexa].origin[index].amount *
        this.carts[indexa].origin[index].product.discount_price;
      // this.carts.forEach(item => {
      //   // console.log(item.amount+'值改变')
      //   const price = item.product.discount_price;
      //   item.totalPrice = NumberMul(item.amount, price).toFixed(2);
      // });
      deitCart(this.carts[indexa].origin[index].id, {
        amount: this.carts[indexa].origin[index].amount
      });
      this.totalAmount();
    },
    totalAmount() {
      console.log("==========================================");
      console.log(this.carts);
      for (let i in this.carts) {
        this.total = parseFloat(
          this.carts[i].origin.reduce((pre, cur) => {
            return NumberAdd(pre, cur.totalPrice);
          }, 0)
        ).toFixed(2);
      }
      // this.total = parseFloat(this.total).toFixed(2)
    },
    // 移除购物车
    async del(item) {
      try {
        await removeCart(item.product_id);
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.fetchCarts();
      } catch (e) {
        console.error(e);
      }
    },
    async addOrder() {
      // const items = []
      // this.carts.forEach(item => {
      //   items.push({
      //     product_id: item.product_id,
      //     amount: item.amount
      //   })
      // })
      // await addOrders({
      //   items,
      //   address_id: this.addressActive,
      //   remark: this.remark
      // })
      console.log(this.checkList);
      this.$router.push(`/check?ids=${this.checkList}`);
    },
    infoBlur() {},
    async addFastCart() {
      const docStr = this.info.replace(/\n(\n)*( )*(\n)*\n/g, "\n");
      try {
        const aIorder = await fastCarts({ info: docStr });
        const goodssuccess = aIorder.success;
        const goodserror = aIorder.error;
        console.log(goodssuccess);
        this.fetchCarts();
        if (goodssuccess !== undefined) {
          for (const i in goodssuccess) {
            console.log(i);
            setTimeout(() => {
              this.$message.success(`添加成功${goodssuccess[i].message}该产品`);
            }, 800);
          }
        }
        if (goodserror !== "") {
          for (const i in goodserror) {
            console.log(i);
            setTimeout(() => {
              this.$message.error(
                `添加失败，暂无${goodserror[i].message}该产品`
              );
            }, 800);
          }
        }
        this.info = "";
      } catch (e) {
        console.log(e);
      }
    },
    open(item) {
      this.$confirm("此操作将删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.del(item);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/order.scss";
.z_icon {
  font-size: 40px;
}
</style>
